qui(function(require, exports, module) {
    Server.ClusterEdit = function(options) {
        this.dao = Server.Dao;
        this.options = $.extend(true, {}, options);

        this.util = Server.Util || {};
        this.config = Server.config || {};

    };

    Com.inherits(Server.ClusterEdit, Ancestor.Grid).extend({
        run: function(options, callback) {
            var self = this;
            var $container = self.options.$container;
            var gridConfig = self.getGridConfig(Server.Config.TABLE_SERVER_IDCSERVER,Server.Config.TABLE_SERVER_IDCSERVER_COLMODEL_CONFIG);

            self.$grid = $container.find('table.grid');

            Server.Dao.clusterList({"pageSize":"300"},function(rdata){
                var names=[];
                var result = rdata['data']['result'];
                for(var i=0;i<result.length;i++){
                    names.push(result[i]['name']);
                }

                self.jumpFromHomePage(function(self,cluster){
                    self.setOptions(self,cluster);
                    var oldName = '';
                    if(cluster){
                        oldName = cluster['name'];
                    }

                    self.perpareData();
                    self.bindEvent(names,oldName);
                });

            });
        },

        perpareData: function() {
            var self = this;
            var username = $("div.user a.name").html();
        },

        bindEvent: function(names,oldName) {
            var self = this;
            var $container = self.options.$container;
            var $submit = $container.find('#Submit');
            var $cluserName = $container.find('input[name="name"]');
            var $idc = $container.find('select[name="idc"]');
            var $flag = $container.find('#flag');
            var validator = self.getValidator();
            var exists=1;
            if(oldName&&oldName!=''){
                exists = 0;
            }
            $idc.change(function() {
                self.query($(this).val());
            });

            $cluserName.on('input',function(){
                if(oldName == $(this).val()||names.indexOf($(this).val())==-1){
                    exists=0;
                    $flag.css('display','none');
                }else{
                    exists=1;
                    $flag.css('display','block');
                    $flag.css('color','red')
                }
            })

            $submit.on('click', function() {
                if(exists==0 || oldName==$cluserName.val()){
                    $submit.html('提交中..');
                    $submit.attr('disabled','disabled');
                    var _save = function(data) {
                        $submit.val('提交中..');
                        if ($('#id').val() != "") {
                            self.editCluster(data);
                        } else {
                            self.addCluster(data);
                        }
                    };

                    var success = validator.form();
                    var data = self.getParam();

                    if (success ){
                        _save(data);
                    }else{
                        $submit.attr('disabled',false);
                        $submit.html('提交');
                    }
                }
            });

        },

        getParam: function(pageSize) {
            var self = this;
            var $container = self.options.$container;

            var $grid = self.$grid;
            var params = {};

            var $elements = $.makeArray($container.prop('elements')).filter(function(item) {
                return true;
            });

            var ids='';
            var name;
            var key;
            $.each($elements, function() {
                name = this.name;
                if (name) {
                    if(name.substr(0,3)=='jqg'){
                        if(this.checked){
                            var id = name.substr(-4);
                            ids+=id+',';
                        }
                    }else{
                        if(name=='id' && $(this).val() == "") {

                        } else {
                            params[name] = $(this).val().trim();
                        }
                    }

                }
            });

            if(ids!=''){
                ids = ids.substr(0,ids.length-1);
                params['serverList'] = ids;
            }
            return params;
        },

        query: function(idc) {
            var self = this;
            var $container = self.options.$container;
            var $grid = self.$grid;
            self.overridePostData($grid);
            $grid.jqGrid('setGridParam', {
                postData: {'idc': idc},
            }).trigger('reloadGrid', [{
                page: 1
            }]);
        },

        getValidator: function() {
            var $container = this.options.$container;
            var $form = $container;
            var validator = Validator.getValidator($form, Server.Config.clusterValidator);

            return validator;
        },

        addCluster: function(data) {
            this.dao.addCluster(data, this.onSave);
        },

        editCluster: function(data) {
            this.dao.editCluster(data, this.onSave);
        },

        onSave: function(json) {
            var $submit = $('#Submit');
            setTimeout(function() {
                $submit.html('提交');
                $submit.attr('disabled',false);
            }, 750);
            if (json.code == 'A00000') {
                var html = '操作成功';
                $(document).tip({
                    content: html,
                    theme: 'success'
                });
                setTimeout(function() {
                    $(window).attr('location','cluster_home.html');
                }, 750);

            } else if(json.data == '-1111'){
                Server.Util.logTips({theme: "error", content: "正在收录任务，不可下线"});
            }else {
                Server.Util.logTips({theme: "error", content: "提交失败"});
            }
        },

        gridComplete: function($container){
            $container.find('tr').each(function(i,ele){
                if(i!=0){
                    if($(ele).find("[aria-describedby='IdcServerListGrid_cluster_name']").eq(0).html()!='未分配集群'){
                        $(ele).find('input').eq(0).attr('disabled',true);
                    };
                }
            });
        },

        jumpFromHomePage: function(callback){
            var url = window.location.href;
            var self = this;
            var $container = self.options.$container;
            if(url.indexOf('?')==-1){
                callback.call(this,self,undefined);
                return;
            }
            var ss = url.split('?')[1];
            var id = ss.split('=')[1];
            Server.Dao.clusterList({'clusterId':id},function(rdata){
                var res = rdata['data']['result'];
                if(res.length>0){
                    var cluster = res[0];
                    $container.find('input[name="name"]').val(cluster['name']);
                    $container.find('input[name="id"]').val(cluster['id']);
                    $container.find('select[name="status"]').val(cluster['status']);
                    $container.find('select[name="idc"]').attr('disabled',true).val(cluster['idc']);
                    callback.call(this,self,cluster);
                }
            });

        },

        setOptions: function(self,cluster){
            var $container = self.options.$container;
            var gridConfig = self.getGridConfig(Server.Config.TABLE_SERVER_IDCSERVER,Server.Config.TABLE_SERVER_IDCSERVER_COLMODEL_CONFIG);
            self.$grid = $container.find('table.grid');
            console.log(cluster);

            var idc ='-- -- -- --';
            var name = '*****';
            if(cluster){
                idc = cluster['idc'];
                name = cluster['name'];
            }

            var options = $.extend(true, {
                width: 370,
                shrinkToFit: false,
                autowidth: false,
                postData: {'idc': idc},
                gridComplete: self.gridComplete($container),
                onSelectAll:function(rowids,status){
                    $container.find('tr').each(function(i,ele){
                        if(i!=0){
                            var nn = $(ele).find("[aria-describedby='IdcServerListGrid_cluster_name']").html();
                            if(nn && nn !='待分配集群' && nn.indexOf(name)==-1){
                                $(ele).removeClass('ui-state-highlight');
                                $(ele).find('input').attr('checked',false);
                                $(ele).find('input').attr('disabled',true);
                            }
                        }
                    });
                },
                onSelectRow:function(rowids,status){
                    var tr = $(this).jqGrid("getInd",rowids,true);
                    var str = $(tr).html();
                    var len = $(tr).find(".assigned").size();
                    if(str.indexOf(name)!=-1){

                    }else if(len>0){
                        $(tr).removeClass('ui-state-highlight');
                        $(tr).removeClass('success');
                        $(tr).find('input').attr({
                            'checked':false,
                            'disabled':true
                        });
                    }
                },
                loadComplete:function(){
                    $container.find('tr').each(function(i,ele){
                        var str = $(ele).html();
                        if(str.indexOf(name)!=-1){
                            var id = $(ele).find('input').attr('id').substr(-4);
                            //console.log(id);
                            self.$grid.jqGrid("setSelection",id);
                        }else if($(ele).find(".assigned").size()>0){
                            $(ele).find('input').attr({
                                'checked':false,
                                'disabled':true
                            });
                        }

                    });
                }
            }, gridConfig, self.options);

            self.$grid.jqGrid(options);
        }
    });

});
